<?php
declare (strict_types=1);

namespace app\client\controller\core;

use app\common\controller\Frontend;
use app\common\enums\AccountTypeEnum;
use app\common\model\banxi\core\CoreTrialClassOrder as CoreTrialClassOrderModel;
use app\common\service\core\TrialClassOrderService;
use app\common\service\queue\QueueService;
use app\common\service\word\WordService;
use ba\Exception;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\facade\Db;

class CoreTrialClassOrder extends Frontend
{
    protected array $noNeedLogin = [];
    protected array $noNeedPermission = [];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new CoreTrialClassOrderModel();
    }


    /**
     * 创建订单
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function placeTrialClassOrder()
    {
        $param = $this->request->param(['expectTime']);
        if (empty($param)) {
            $this->fail('请传递参数');
        }
        $studentId = $this->auth->id;
        if (empty($studentId)) {
            $this->fail('请设置学生');
        }
        Db::startTrans();
        try {
            $trialClassOrderService = new TrialClassOrderService();
            $orderId = $trialClassOrderService->place($studentId, $param, AccountTypeEnum::STUDENT);
            Db::commit();
        } catch (Exception|PDOException|ValidateException $e) {
            Db::rollback();
            $this->fail($e->getMessage());
        }
        $this->ok('操作成功', $orderId);
    }

    /**
     * 支付订单
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function pay()
    {
        $param = $this->request->param(['orderId', 'payType']);
        if (empty($param['orderId'])) {
            $this->fail('请选择支付的订单');
        }
        if (empty($param['payType'])) {
            $this->fail('请选择支付方式');
        }
        $studentId = $this->auth->id;
        Db::startTrans();
        try {
            $trialClassOrderService = new TrialClassOrderService();
            $info = $trialClassOrderService->payInitiate($studentId, $param['orderId'], $param['payType'], 'wxMini');
            Db::commit();
        } catch (Exception|PDOException|ValidateException $e) {
            Db::rollback();
            $this->fail($e->getMessage());
        }
        $this->ok('操作成功', $info);
    }
}
